import { configs } from '@/assets/config/config.js';

/**
 * 判断值为空
 * @param val: 要验证的值
 */
export function YD_isEmpty(val) {
	if (val === 0) return false;
	// null or undefined
	if (val == null) return true;

	if (typeof val === 'boolean') return false;

	if (typeof val === 'number') return !val;

	if (val instanceof Error) return val.message === '';

	switch (Object.prototype.toString.call(val)) {
		// String or Array
		case '[object String]':
		case '[object Array]':
			return !val.length;

			// Map or Set or File
		case '[object File]':
		case '[object Map]':
		case '[object Set]': {
			return !val.size;
		}
		// Plain Object
		case '[object Object]': {
			return !Object.keys(val).length;
		}
	}

	return false;
}

/**
 * 防抖
 * @param fn
 * @param wait
 * @returns {Function}
 */
export function YD_debounce(fn, wait = 250) {
	let timer = null;
	return function (...arg) {
		if(timer) clearTimeout(timer);
		timer = setTimeout(() => {
			fn.apply(this, arg)
		}, wait);
	}
}

/**
 * @name 处理文件地址
 * @param { String } path
 * @returns
 */
export function YD_formatUrl (path) {
  const linkReg = /https?:\/\//i
  const baseUrl = configs.BASE_URL
  return linkReg.test(path) ? path : (path.indexOf(baseUrl) === -1 ? (baseUrl + path) : path)
}

/**
 * @name 比较两个时间大小
 * @param {*} date1
 * @param {*} date2
 * @param {*} compareTime: 是否比较时间, 默认不比较
 * @returns
 */
exports.YD_compareDate = (date1, date2 = new Date(), compareTime = false) => {
  let flag = null;
  if(!date1) {
    console.warn('请输入比较的日期');
    return;
  }
  if(!(date1 instanceof Date)) {
    date1 = new Date(date1.replace(/-/g,"\/"));
  }
  if(!(date2 instanceof Date)) {
    date2 = new Date(date2.replace(/-/g,"\/"));
  }
  // 不比较时间,只比较日期
  if(!compareTime) {
    date1 = new Date(date1.getFullYear() + '/' + (date1.getMonth()+1) + '/' + date1.getDate());
    date2 = new Date(date2.getFullYear() + '/' + (date2.getMonth()+1) + '/' + date2.getDate());
  }
  if(date1.getTime() < date2.getTime()){
    flag =  -1;
  }else if(date1.getTime() == date2.getTime()) {
    flag =  0;
  }else {
    flag =  1;
  }
  return flag;
}
